# -*- coding: UTF-8 -*-

from random import randint

__author__ = 'Jinkey'

# ==========================================
# |为那些词的边界没有任何视觉表示的书写系统分词|
# ==========================================

class AnnealingText(object):
    def __init__(self, text):
        self.text = text
        self.seg = '0' * (len(self.text) - 1)

    @staticmethod
    def segment(text, segments):
        words = []
        last = 0
        for i in range(len(segments)):
            if segments[i] == '1':
                words.append(text[last:i + 1])
                last = i + 1
        words.append(text[last:])
        return words

    def evaluate(self, text, segments):
        words = self.segment(text, segments)
        text_size = len(words)
        lexicon_size = len(''.join(list(set(words))))
        return text_size + lexicon_size

    @staticmethod
    def filp(segments, pos):
        return segments[:pos] + str(1 - int(segments[pos])) + segments[pos + 1:]

    def filp_n(self, segments, n):
        for i in range(n):
            segments = self.filp(segments, randint(0, len(segments) - 1))
        return segments

    def anneal(self, iterations, cooling_rate):
        segments = self.seg
        temperature = float(len(segments))
        while temperature > 0.5:
            best_segs, best = segments, self.evaluate(self.text, segments)
            for i in range(iterations):
                guess = self.filp_n(segments, int(round(temperature)))
                score = self.evaluate(self.text, guess)
                if score < best:
                    best, best_segs = score, guess
            score, segments = best, best_segs
            temperature = temperature / cooling_rate
            print temperature, self.evaluate(self.text, segments), self.segment(self.text, segments)
        print '-END--'
        return segments
